import axios, { type AxiosRequestConfig } from 'axios'

export type ResponseType<DataType = unknown> = {
  code: string | number
  message?: string
  msg?: string
  data: DataType
}


export const createInstance = (baseURL: string) => {
  const instance = axios.create({ baseURL })
  instance.interceptors.request.use((config) => {
    return config
  }, err => {
    return Promise.reject(err)
  })
  return <DataType = any>(config: AxiosRequestConfig): Promise<ResponseType<DataType>> =>
    instance(config)
      .then(({ data }) => data)
      .then((res) => {

        const { code, message, msg } = res
        if (code === 200) {
          return res
        } else {
          return Promise.reject(new Error(message || msg))
        }
      })
      .catch((err) => {
        return Promise.reject(new Error(err))
      })
}

export const request = createInstance('')